package com.karrysong.blog_springboot.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.karrysong.blog_springboot.entity.*;
import com.karrysong.blog_springboot.enums.ErrorCode;
import com.karrysong.blog_springboot.mapper.ArticleMapper;
import com.karrysong.blog_springboot.mapper.CommentMapper;
import com.karrysong.blog_springboot.service.CommentService;
import com.karrysong.blog_springboot.service.UserService;
import com.karrysong.blog_springboot.util.UserThreadLocal;
import com.karrysong.blog_springboot.vo.CommentVo;
import com.karrysong.blog_springboot.vo.Result;
import com.karrysong.blog_springboot.vo.UserVo;
import com.karrysong.blog_springboot.vo.params.CommentPage;
import com.karrysong.blog_springboot.vo.params.CommentParam;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: CommentServiceImpl
 * @Author: KarrySong
 * @Date: 2022/8/6 14:25
 * @Description:
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserService userService;

    public CommentVo copy(Comment comment){
        CommentVo commentVo = new CommentVo();
        BeanUtils.copyProperties(comment,commentVo);
        commentVo.setId(comment.getId());
        //时间格式化
        commentVo.setCreateDate(new DateTime(comment.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        Long authorId = comment.getAuthorId();
        UserVo userVo = userService.copy(userService.findUserById(authorId));
        commentVo.setAuthor(userVo);
        //评论的评论
        List<CommentVo> commentVoList = findCommentsByParentId(comment.getId());
        commentVo.setChildrens(commentVoList);
        if (comment.getLevel() > 1) {
            UserVo toUserVo = userService.copy(userService.findUserById(authorId));
            commentVo.setToUser(toUserVo);
        }
        return commentVo;
    }

    private List<CommentVo> findCommentsByParentId(Long id) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        //二级评论
        queryWrapper.eq(Comment::getParentId,id);
        queryWrapper.eq(Comment::getLevel,2);
        queryWrapper.eq(Comment::getStatus, 1);
        List<Comment> comments = this.commentMapper.selectList(queryWrapper);
        return copyList(comments);
    }

    @Override
    public Result getComments(CommentPage commentPage) {
        Page<Comment> page = new Page<>(commentPage.getPage(), commentPage.getPageSize());
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(commentPage.getLevel() != null, Comment::getLevel, commentPage.getLevel());
        wrapper.eq(commentPage.getAuthorId() != null, Comment::getAuthorId, commentPage.getAuthorId());
        wrapper.eq(commentPage.getArticleId() != null, Comment::getArticleId, commentPage.getArticleId());
        wrapper.ge(commentPage.getTimeStart() != null, Comment::getCreateDate, commentPage.getTimeStart());
        wrapper.le(commentPage.getTimeEnd() != null, Comment::getCreateDate, commentPage.getTimeEnd());
        IPage<Comment> pageResult = commentMapper.selectPage(page, wrapper);
        List<Comment> records = pageResult.getRecords();
        List<CommentVo> articleVoList = copyList(records);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentList", articleVoList);
        jsonObject.put("pageData", pageResult);
        return Result.success(jsonObject);
    }

    @Override
    public Result changeCommentStatus(Long id, Integer newStatus) {
        Comment comment = new Comment();
        comment.setId(id);
        comment.setStatus(newStatus);
        int i = commentMapper.updateById(comment);
        if (i > 0){
            return Result.success(null);
        }else {
            return Result.fail(ErrorCode.ADMIN_ERROR, "修改评论状态失败");
        }
    }

    @Override
    public Result deleteComment(Long id) {
        int i = commentMapper.deleteById(id);
        if (i > 0){
            /**
             * 此处还需考虑删除的是一级评论情况下，怎么处理对应二级评论
             */
            return Result.success(null);
        }else {
            return Result.fail(ErrorCode.ADMIN_ERROR, "删除评论失败");
        }
    }

    public List<CommentVo> copyList(List<Comment> commentList){
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment : commentList) {
            commentVoList.add(copy(comment));
        }
        return commentVoList;
    }

    @Override
    public Result commentsByArticleId(Long articleId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getArticleId,articleId);
        queryWrapper.eq(Comment::getStatus, 1);
        //一级评论
        queryWrapper.eq(Comment::getLevel,1);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return Result.success(copyList(comments));
    }

    @Override
    public Result comment(CommentParam commentParam) {
        User sysUser = UserThreadLocal.get();
        Comment comment = new Comment();
        comment.setArticleId(commentParam.getArticleId());
        comment.setAuthorId(sysUser.getId());
        comment.setContent(commentParam.getContent());
        comment.setCreateDate(System.currentTimeMillis());
        comment.setStatus(1);
        Long parent = commentParam.getParent();
        if (parent == null || parent == 0) {
            comment.setLevel(1);
        }else{
            comment.setLevel(2);
        }
        comment.setParentId(parent == null ? 0 : parent);
        Long toUserId = commentParam.getToUserId();
        //可以使用文章作者id
        comment.setToUid(toUserId == null ? 0 : toUserId);
        this.commentMapper.insert(comment);

        //修改文章评论量
        //1.查询该文章总评论量
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getArticleId, comment.getArticleId());
        List<Comment> comments = commentMapper.selectList(wrapper);
        System.out.println("评论数：" + comments.size());
        //2.修改文章评论量
        Article article = new Article();
        article.setId(comment.getArticleId());
        article.setCommentCounts(comments.size());
        int i = articleMapper.updateById(article);
        System.out.println("修改结果：" + i);

        return Result.success(null);
    }

    public static void main(String[] args) {
        String time = "2022-08-23T01:59:40.000Z";
        Date date = new Date(time);
        System.out.println(date);
    }
}
